// package/pages/recharge/recharge.js
const utils = require('../../../utils/util.js');
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
let login = require('../../../common/script/login');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    objectArray: [],
    couponList: [],
    money: '',
    id: '',
    memberData: null,
    orgcode: "",
    priceType: 1,
    ysfsaledes: 0,
    ysfsale: false,
    ysfsalerus: [],
    showHint: false
  },
  //支付方式
  onPriceType(e) {
    const that = this;
    let type = e.currentTarget.dataset.type
    that.setData({
      priceType: type
    })
  },
  //获取余额
  // getCardinfoData() {
  //   const that = this;
  //   let data = {
  //     token: wx.getStorageSync('token'),
  //   }
  //   myRequest.EasyHttp.post(api.reqUrls.membercardShow, data).then(res => {
  //     if (res.data.status == 1) {
  //       that.setData({
  //         memberData: res.data.result.member_data,
  //       })
  //     } else {
  //       wx.showModal({
  //         content: res.data.msg,
  //         showCancel: false,
  //         confirmText: '我知道了',
  //         confirmColor: '#ff5151',
  //         success(e) {
  //           //返回tab页面刷新数据
  //           wx.setStorageSync('refresh', true)
  //           //返回优惠券页面刷新数据
  //           wx.setStorageSync('refreshCoupon', true)
  //           wx.navigateBack({
  //             delta: 1
  //           })
  //         }
  //       })
  //     }
  //   })

  // },
  //获取充值金额列表
  getProvince() {
    const that = this;
    let data = {
      token: wx.getStorageSync('token'),
      orgcode: that.data.orgcode,
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getInMoneyTypeNew, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        var data = res.data.result.money_type;
        if (data) {
          var monerArr = [];
          for (var i = 0; i < data.length; i++) {
            var dec = {
              'id': data[i]['id'],
              'name': data[i]['money'],
              'des': data[i]['money'] + '元 ',
              'checked': false,
              couponList: data[i]['couponList']
            }
            monerArr.push(dec)
          }
          monerArr[0].checked = true;
          that.setData({
            money: monerArr[0].name,
            id: monerArr[0].id,
            objectArray: monerArr,
            couponList: monerArr[0].couponList,
            ysfsaledes: res.data.result.ysfsaledes,
            ysfsale: res.data.result.ysfsale,
            ysfsalerus: res.data.result.ysfsalerus
          })
        }
      }

    })
  },
  //选择充值金额
  selectPrice(e) {
    let id = e.currentTarget.dataset.id
    var name = '';
    let couponList = []
    for (let i = 0; i < this.data.objectArray.length; i++) {
      if (this.data.objectArray[i].id == id) {
        //当前点击的位置为true即选中
        this.data.objectArray[i].checked = true;
        name = this.data.objectArray[i].name;
        couponList = this.data.objectArray[i].couponList;
      } else {
        //其他的位置为false
        this.data.objectArray[i].checked = false;
      }
    }
    this.setData({
      couponList,
      id,
      money: name,
      objectArray: this.data.objectArray,
    })
  },
  //充值
  debounces: utils.throttle(function (e) {
    this.recharge()
  }, 5000),
  recharge() {
    const that = this;
    if (that.data.priceType == 1) {
      let data = {
        orgcode: that.data.orgcode,
        token: wx.getStorageSync('token'),
        money: that.data.money,
        recharge_money_type_id: that.data.id,
        pay_h_type: 'wx'
      }
      wx.showLoading({
        title: '加载中...',
      })
      myRequest.EasyHttp.post(api.reqUrls.rechargeDopay, data).then(res => {
        wx.hideLoading();
        if (res.data.status == 1) {
          wx.requestPayment({ // 调取支付
            appId: res.data.result.wx.appId,
            timeStamp: res.data.result.wx.timeStamp.toString(),
            nonceStr: res.data.result.wx.nonceStr,
            package: res.data.result.wx.package,
            signType: res.data.result.wx.signType,
            paySign: res.data.result.wx.sign,
            success(prop) {
              if (prop.errMsg == "requestPayment:ok") {
                // that.getLeshuacheck(res.data.result.order)

                let type = that.data.couponList.length > 0 ? 1 : 2
                setTimeout(() => {
                  wx.redirectTo({
                    url: `/package/pages/rechargeSuccess/rechargeSuccess?orderId=${res.data.result.order}&type=${type}`
                  })
                }, 500)
              } else {
                wx.showModal({
                  content: res.errMsg,
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {}
                })
              }
            },
            fail(res) {
              console.log(res, 77)
              if (res.errMsg == "requestPayment:fail cancel") {
                wx.showToast({
                  title: '支付取消',
                  duration: 2200
                })
              }
            }
          })

        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff5151',
            success(e) {}
          })

        }
      })
    } else {
      let data = {
        orgcode: that.data.orgcode,
        token: wx.getStorageSync('token'),
        money: that.data.money,
        recharge_money_type_id: that.data.id,
        pay_h_type: 'wxminiysf'
      }
      wx.showLoading({
        title: '加载中...',
      })
      myRequest.EasyHttp.post(api.reqUrls.rechargeDopay, data).then(res => {
        wx.hideLoading();
        if (res.data.status == 1) {
          wx.openEmbeddedMiniProgram({
            appId: res.data.result.wx.union_app_id,
            path: res.data.result.wx.union_path,
            extraData: {
              autoPay: 1,
            },
            envVersion: 'release',
            success(resData) {
              console.log(resData, 89898989)
              // 打开成功
              var listener = (props) => {
                console.log(props, 111)
                if (props.scene == 1038) {
                  wx.showModal({
                    content: '是否支付成功?',
                    cancelText: "未支付",
                    cancelColor: "#F56C6C",
                    confirmText: '已支付',
                    confirmColor: '#67C23A',
                    success(e) {
                      if (e.confirm) {
                        let type = that.data.couponList.length > 0 ? 1 : 2
                        setTimeout(() => {
                          wx.redirectTo({
                            url: `/package/pages/rechargeSuccess/rechargeSuccess?orderId=${res.data.result.order}&type=${type}`
                          })
                        }, 500)
                      }
                    }
                  })

                  // that.getLeshuacheck(res.data.result.order)

                }
                if (listener) {
                  wx.offAppShow(listener)
                }
              };
              wx.onAppShow(listener)
            },
            fail(e) {
              console.log(e, 999999)
              // 打开失败
            },
          })

        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff5151',
            success(e) {}
          })

        }
      })
    }

  },
  showYsfsaledes() {
    const that = this;
    that.setData({
      showHint: true
    })
  },
  hideYsfsaledes() {
    const that = this;
    that.setData({
      showHint: false
    })
  },
  // getLeshuacheck(order_id) {
  //   const that = this;
  //   let data = {
  //     token: wx.getStorageSync('token'),
  //     order_id
  //   }
  //   myRequest.EasyHttp.post(api.reqUrls.leshuacheck, data).then(res => {})
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this
    if (options.scene) {
      let sceneObj = utils.parseQueryString(options.scene)
      that.setData({
        orgcode: sceneObj.orgcode
      })
    } else if (options.q) {
      let scene = decodeURIComponent(options.q)
      const url = scene.substring(scene.indexOf('?') + 1)
      const params = url.split('&')
        .reduce(function (acc, param) {
          const [key, value] = param.split('=');
          acc[key] = decodeURIComponent(value);
          return acc;
        }, {});
      console.log(params, 123)
      let orgcode = params['orgcode'];
      that.setData({
        orgcode: orgcode
      })
    }
    let memberData = wx.getStorageSync('memberData')
    login.checkLogin().then(res => {
      // that.getCardinfoData()
      that.setData({
        memberData: memberData,
      })
      that.getProvince()
    }).catch(err => {
      app.appCallBack = (e) => {
        // that.getCardinfoData()
        that.setData({
          memberData: memberData,
        })
        that.getProvince()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})